//
//  EmotionView.swift
//  01-表情键盘
//
//  Created by 002 on 15/10/24.
//  Copyright © 2015年 002. All rights reserved.
//

import UIKit

let emotionViewCellId = "emotionViewCellId"
class EmoticonView: UIView {

    // 选中表情后的回调
    private var selectedEmotionCallBack: (emoticon : Emoticon) ->()
    
    // MARK: - 监听方法
    @objc private func clickItem(item: UIBarButtonItem) {
        print("选中分类 \(item.tag)")
        
        // 跳到对应的分组表情
        let indexPath = NSIndexPath.init(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    
    // MARK:构造函数
    init(selectedEmotion : (emoticon : Emoticon)->()) {

        // 记录闭包属性
        selectedEmotionCallBack = selectedEmotion
        
        // 调用父类的构造函数
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        super.init(frame: rect)
        
        // 设置UI
        setupUI()
        
        // 跳到有表情的第一页
        let indexPath = NSIndexPath.init(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK:懒加载控件
    // 工具栏
    private lazy var toobBar = UIToolbar()
    // 表情视图
    private lazy var collectionView = UICollectionView.init(frame: CGRectZero, collectionViewLayout: EmotionLayout())
    // 表情包数组
    private lazy var packages : [EmoticonPackage] = EmoticonManager.sharedManager.packages
    
    // 表情布局（类中类，只允许被包含的类使用）
    private  class EmotionLayout : UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            super.prepareLayout()
            
            let row : CGFloat = 3
            let col : CGFloat = 7
            
            // 计算宽度
            let w = (collectionView?.bounds.width)! / col
            
            // 边距
            let margin = ((collectionView?.bounds.height)! - row * w) * 0.499
            itemSize = CGSizeMake(w, w)
            
            // 每个item的间距
            sectionInset = UIEdgeInsetsMake(margin, 0, margin, 0)
            
            // 设置布局属性
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.bounces = false
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}

// MARK:设置界面
extension EmoticonView {

    // MARK:设置UI
    private func setupUI() {
        
        // 1. 添加控件
        addSubview(collectionView)
        addSubview(toobBar)
        
        // 2. 布局
        // 表情工具栏
        toobBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        
        // 表情视图
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toobBar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }
        
        // 准备表情视图
        prepareForCollectionView()
        // 准备工具栏
        prepareForToolBar()
    }
    
    // MARK:准备工具栏
    private func prepareForToolBar() {
        
        // 设置渲染颜色
        toobBar.tintColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        // 遍历创建item
        for p in packages {
            items.append(UIBarButtonItem.init(title: p.group_name_cn, style: .Plain, target: nil, action: "clickItem:"))
            items.last?.tag = index++
            // 添加弹簧按钮
            items.append(UIBarButtonItem.init(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        // 设置工具栏的items
        toobBar.items = items
    }
    
    // MARK:准备表情视图
    private func prepareForCollectionView() {
        
        // 设置背景色
        collectionView.backgroundColor = UIColor.lightGrayColor()
        
        // 设置数据源 和 代理
        collectionView.dataSource = self
        collectionView.delegate = self
        
        // 注册cell
        collectionView.registerClass(EmotionViewCell.self, forCellWithReuseIdentifier: emotionViewCellId)
    }
}

// MARK:数据源方法
extension EmoticonView : UICollectionViewDataSource,UICollectionViewDelegate {
    
    // 选中item后的操作
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取表情模型
        let em = packages[indexPath.section].emoticons[indexPath.item]
        
        // 执行‘回调’
        selectedEmotionCallBack(emoticon: em)
    }
    
    // Section 个数
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    // Section下的 Item 个数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    // 返回item
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emotionViewCellId, forIndexPath: indexPath) as! EmotionViewCell
        cell.backgroundColor = UIColor.RandomColor()        
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        //        print("\(indexPath.row)-------\(cell)------\(cell.emotionButton)")
        return cell
    }
}

// MARK:表情视图 Cell
private class EmotionViewCell : UICollectionViewCell {
    
    var emoticon : Emoticon? {
        didSet {
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            emoticonButton.setImage(UIImage.init(contentsOfFile: (emoticon?.imagePath)!), forState: UIControlState.Normal)
            
            if emoticon!.isRemoved {
                emoticonButton.setImage(UIImage.init(named: "compose_emotion_delete_highlighted"),forState: UIControlState.Normal)
            }
            // 设置 emoji，千万不要加上判断，否则显示会不正常
            if emoticon?.emoji != nil {
            }
        }
        
    }
    
    //MARK: 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 添加控件
        addSubview(emoticonButton)
        
        // 字体的大小和高度相近
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        // 设置按钮不可交互是为了点击的时候能够执行到didSelectItemAtIndexPath
        emoticonButton.userInteractionEnabled = false
        
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.setTitleColor(UIColor.RandomColor(), forState: UIControlState.Normal)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: 懒加载控件
    private lazy var emoticonButton : UIButton = UIButton()
}

